<!--
 * @Author: Lee
 * @Date: 2023-07-11 09:30:38
 * @LastEditors: Lee
 * @LastEditTime: 2023-07-11 10:46:03
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>数组转树结构</title>
</head>

<body>


  <script>


    function buildTree(arr) {
      const treeMap = {};
      const root = [];

      // 构建映射表
      for (const node of arr) {
        const { id, name, parentId } = node;
        treeMap[id] = { id, name, children: [] };
        if (parentId === 0) {
          root.push(treeMap[id]);
        }
      }

      // 将节点添加到对应的父节点下
      for (const node of arr) {
        const { id, parentId } = node;
        if (parentId !== 0) {
          treeMap[parentId].children.push(treeMap[id]);
        }
      }

      return root;
    }

    // 示例用法
    const arr = [
      { id: 2, name: '部门B', parentId: 0 },
      { id: 3, name: '部门C', parentId: 1 },
      { id: 1, name: '部门A', parentId: 2 },
      { id: 4, name: '部门D', parentId: 1 },
      { id: 5, name: '部门E', parentId: 2 },
      { id: 6, name: '部门F', parentId: 3 },
      { id: 7, name: '部门G', parentId: 2 },
      { id: 8, name: '部门H', parentId: 4 },
    ];

    const tree = buildTree(arr);
    console.log(tree);


  </script>
</body>

</html>